package br.com.amadeus.android.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.amadeus.android.entities.Role;

public class RoleDAO {

	public static String[] columns = new String[] { RoleDAO.ID, RoleDAO.VALUE, RoleDAO.AMADEUS_ID};

	public static final String ID = "_id";
	public static final String AMADEUS_ID = "amadeus_id";
	public static final String VALUE = "value";

	private SQLiteDatabase db;

	private static RoleDAO instance = new RoleDAO();

	public static RoleDAO getInstance(Context ctx) {

		if (instance.db == null || !instance.db.isOpen()) {
			instance.db = new DBHelper(ctx).getWritableDatabase();
		}
		return instance;
	}

	private RoleDAO() {
	}

	public long save(Role role) {
		long id = role.getId();
		if (id == 0) {
			return insert(role);
		} else {
			return update(role);
		}
	}

	private long insert(Role role) {
		long id_role = -1;

		db.beginTransaction();
		try {

			ContentValues values = new ContentValues();
			values.put(RoleDAO.VALUE, role.getValue());
			values.put(RoleDAO.AMADEUS_ID, role.getAmadeus_id());

			id_role = db.insert(DBHelper.TABLE_ROLE, null, values);
			
			if (id_role != -1)
				db.setTransactionSuccessful();

		} finally {
			db.endTransaction();
		}

		return id_role;
	}

	private long update(Role role) {
		boolean deuErro = false;
		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put(RoleDAO.VALUE, role.getValue());
			values.put(RoleDAO.AMADEUS_ID, role.getAmadeus_id());

			deuErro = db.update(DBHelper.TABLE_ROLE, values, RoleDAO.ID
					+ " = ?", new String[] { String.valueOf(role.getId()) }) == 0;

			if (!deuErro)
				db.setTransactionSuccessful();

		} finally {
			db.endTransaction();
		}
		return role.getId();
	}

	public void delete(int id) {
		db.beginTransaction();
		try {
			db.delete(DBHelper.TABLE_ROLE, RoleDAO.ID + "=?",
					new String[] { String.valueOf(id) });
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}
	
	public Role getRole(int id){
		Cursor c = db.query(DBHelper.TABLE_ROLE, null, RoleDAO.ID + "=" + id,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			return fillRole(c);
		}
		return null;
	}
	
	protected static Role fillRole(Cursor c){
		int id = c.getInt(c.getColumnIndex(RoleDAO.ID));
		String value = c.getString(c.getColumnIndex(RoleDAO.VALUE));
		int amadeus_id = c.getInt(c.getColumnIndex(RoleDAO.AMADEUS_ID));
		return new Role(id, value, amadeus_id);
	}

}
